package com.qn.util;

import cn.hutool.extra.spring.SpringUtil;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 获取i18n资源文件
 *
 * @author QN
 * @date 2024/12/31
 */
@Component
public class MessageUtils {

    private static final MessageSource MESSAGE_SOURCE = SpringUtil.getBean(MessageSource.class);

    /**
     * 根据消息键和参数 获取消息 委托给spring messageSource
     *
     * @param code 消息键
     * @param args 参数
     * @return 获取国际化翻译值
     */
    public static String message(String code, Object... args) {
        try {
            return MESSAGE_SOURCE.getMessage(code, args, LocaleContextHolder.getLocale());
        } catch (NoSuchMessageException e) {
            return code;
        }
    }

    public static Map<String, String> getAllMessages() {
        //存放所有message
        Map<String, String> messages = new HashMap<>();

        ResourceBundleMessageSource bundleMessageSource = (ResourceBundleMessageSource) MESSAGE_SOURCE;
        String[] baseNames = bundleMessageSource.getBasenameSet().toArray(new String[0]);

        for (String baseName : baseNames) {
            //从缓存中获取资源文件
            ResourceBundle resourceBundle = ResourceBundle.getBundle(baseName, LocaleContextHolder.getLocale());
            //获取资源文件的所有code
            Set<String> keys = resourceBundle.keySet();

            for (String key : keys) {
                //根据code获取对应的message
                String message = MESSAGE_SOURCE.getMessage(key, null, LocaleContextHolder.getLocale());
                messages.put(key, message);
            }
        }
        return messages;
    }

}

